package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.comment.pojos.ApComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentHotServiceImpl implements CommentHotService {
    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 查找热点评论  热点评论不超过过5条
     *
     * @param entryId
     * @param apComment
     */
    @Override
    @Async("taskExecutor")
    public void hotCommentExecutor(Long entryId, ApComment apComment) {
        //查询当前 文章热点评论所有数据，并按照点赞数倒排
        List<ApComment> commentHotList = mongoTemplate.find(
                Query.query(
                        Criteria.where("entryId").is(entryId)
                                .and("type").is(0)
                                .and("flag").is(1)
                ).with(Sort.by(Sort.Direction.DESC, "likes"))
                , ApComment.class
        );
        //如果当前没有热点数据，或者热点数量小于5条，直接新增
        if (commentHotList==null || commentHotList.size()<=4){
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            return;
        }
        //否则热点数就是5条，需要判断和热点最后一条对比
        ApComment lastHotComment = commentHotList.get(commentHotList.size() - 1);
        if (lastHotComment.getLikes()<apComment.getLikes()){
            lastHotComment.setFlag((short) 0);
            mongoTemplate.save(lastHotComment);//设为不是热点
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);//设为热点
        }
    }
}